package net.hanjava.swing;

import static java.awt.RenderingHints.KEY_ANTIALIASING;
import static java.awt.RenderingHints.VALUE_ANTIALIAS_ON;

import java.awt.Color;
import java.awt.Component;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.RenderingHints;
import java.awt.Window;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolTip;
import javax.swing.SwingUtilities;
import javax.swing.border.Border;

import com.sun.jna.examples.WindowUtils;

/**
 * - Rounded tooltip
 * - Antialiasing
 * - Transcluent for lightweight popup
 * - Transcluent for heavyweight popup
 */
public class TooltipExample2 {
	@SuppressWarnings("serial")
	static class CustomTooltip extends JToolTip {
		private static final Border BORDER_NONE = BorderFactory
				.createEmptyBorder(5, 5, 5, 5);
		private static final Color TRANSCLUENT_BLACK = new Color(0f, 0f, 0f,
				0.5f);

		public CustomTooltip() {
			// prevent fillrect for background
			setOpaque(false);
			setBorder(BORDER_NONE);
		}

		@Override
		protected void paintComponent(Graphics g) {
			Graphics2D g2 = (Graphics2D) g;
			RenderingHints orgHints = g2.getRenderingHints();
			g2.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON);

			g.setColor(TRANSCLUENT_BLACK);
			g.fillRoundRect(0, 0, getWidth(), getHeight(), 10, 10);
			g.setColor(Color.WHITE);
			FontMetrics fm = g.getFontMetrics();
			Insets mg = getInsets();
			int tm = mg.top;
			int lm = mg.left;
			// '3' is hardcoded at BasicToolTipUI
			g.drawString(getTipText(), 3 + lm, fm.getAscent() + tm);

			g2.setRenderingHints(orgHints);
		}

		@Override
		public void addNotify() {
			super.addNotify();
			// popup's window
			Window w = SwingUtilities.windowForComponent(this);
			if(isPopupHeavy(w)) {
				WindowUtils.setWindowTransparent(w, true);
			}
		}

		private boolean isPopupHeavy(Window w) {
			// JButton, for example
			Component source = getComponent();
			Window sw = SwingUtilities.windowForComponent(source);
			return w!=sw;
		}
	}

	@SuppressWarnings("serial")
	static class CustomButton extends JButton {
		public CustomButton(String text) {
			super(text);
			setToolTipText(text + " tooltip");
			setBackground(Color.WHITE);
		}

		@Override
		public JToolTip createToolTip() {
			JToolTip tt = new CustomTooltip();
			tt.setComponent(this);
			return tt;
		}
	}

	public static void main(String[] args) {
		Util.ensureSwingInit();
		JPanel cp = new JPanel(new GridLayout(1, 2));
		JButton bt1 = new CustomButton("piglet");
		JButton bt2 = new CustomButton("pooh");
		cp.add(bt1);
		cp.add(bt2);
		Util.show(cp, 100, 100, 300, 300);
		System.err.println(Util.getAllWindows());
	}
}